package com.example.management.system.config

import com.example.management.common.annotation.Log
import com.example.management.common.controller.BaseController
import com.example.management.common.service.FileService
import com.example.management.common.utils.MD5Utils
import com.example.management.common.utils.R
import com.example.management.common.utils.ShiroUtils
import com.example.management.system.service.MenuService
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.UsernamePasswordToken
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

import org.springframework.ui.Model


@Controller
class LoginController : BaseController() {

    @Autowired
    lateinit var menuService : MenuService;

    @Autowired
    lateinit var fileService : FileService;

    @GetMapping(value = ["/",""])
    fun welcome() : String {
        return "redirect:/blog";
    }

    @GetMapping("/login")
    fun login(): String {
        return "login"
    }

    @Log("请求访问主页")
    @GetMapping("/index")
    fun index(model: Model): String {
        val menus = menuService.listMenuTree(getUserId())
        model.addAttribute("menus", menus)
        model.addAttribute("name", getUser().name)
        model.addAttribute("deviceCount",100)
        val fileDO = fileService.get(getUser().picId)
        if (fileDO != null && fileDO!!.url != null) {
            if (fileService.isExist(fileDO!!.url)!!) {
                model.addAttribute("picUrl", fileDO!!.url)
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg")
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg")
        }
        model.addAttribute("username", getUser().username)
        return "index_v1"
    }

    @GetMapping("/logout")
    fun logout(): String {
        ShiroUtils.logout()
        return "redirect:/login"
    }

    @GetMapping("/main")
    fun main(model: Model): String {
        model.addAttribute("deviceCount",100)
        return "main"
    }

    @PostMapping("/login")
    @ResponseBody
    fun login(@RequestParam username:String?, @RequestParam password:String?): R {
        val encrypt = MD5Utils.encrypt(username!!, password!!);
        val token:UsernamePasswordToken = UsernamePasswordToken(username,encrypt)
        val subject = SecurityUtils.getSubject()
        try {
            subject.login(token)
            return R.ok();
        }catch (e : AuthenticationException){
            return R.error("用户或密码错误")
        }
    }

}
